/*
 *    FPTreeHeaders.java
 *    Copyright (C) 2011 University of Waikato, Hamilton, New Zealand
 *    @author Maciek Jarka (www.admire-project.eu)
 *
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
package moa.associations;

import java.util.ArrayList;
import java.util.List;

import weka.associations.Item;

public class FPTreeHeaders {

    List<FPNode> headers;

    public FPTreeHeaders() {
        headers = new ArrayList<FPNode>();
    }

    public void add(FPNode node) {
        if (!headers.contains(node)) {
            headers.add(node);
            return;
        }
        FPNode head = headers.get(headers.indexOf(node));
        while (head.nextHeader != null) {
            head = head.nextHeader;
        }
        head.nextHeader = node;
        return;
    }

    public int calculateSupport(List<Item> items) {
        int support = 0;

        int id = headers.indexOf((new FPNode(items.get(0), null)));
        if (id == -1) {
            return 0;
        }
        FPNode node = headers.get(id);
        if (node == null) {
            return 0;
        }
        do {
            support += node.calculateSupport(items);
            node = node.nextHeader;
        } while (node != null);
        return support;

    }

    public int calculateTidSum(List<Item> items) {
        int tidsum = 0;
        int id = headers.indexOf((new FPNode(items.get(0), null)));
        if (id == -1) {
            return 0;
        }
        FPNode node = headers.get(id);
        if (node == null) {
            return 0;
        }
        do {
            tidsum += node.calculateTidSum(items);
            node = node.nextHeader;
        } while (node != null);
        return tidsum;

    }

    public Transaction remove(int tid) {
        FPNode tail = FPNode.tidmap.get(Integer.valueOf(tid));
        List<Item> items = new ArrayList<Item>();
        while (tail.item != null && tail.tidlist.contains(tid)) {
            tail.support--;
            tail.tidsum -= tid;
            tail.tidlist.remove(Integer.valueOf(tid));
            items.add(tail.item);
            tail = tail.parent;
        }
        return new Transaction(tid, items);
    }
}
